package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.extension.repository.AbstractRepository;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.Like;
import com.yami.shop.common.constants.RedisKeys;
import com.yami.shop.dao.LikeMapper;
import com.yami.shop.service.LikeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用于存储用户对动态的点赞记录 服务实现类
 * </p>
 *
 * @author EXiaoKe
 * @since 2025-04-14
 */
@Service
@Slf4j
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private  RedisScript<Long> likeScript;
    @Resource
    private  RedisScript<Long> unlikeScript;




    /**
     * 点赞或取消点赞
     *
     * @param postId 内容ID
     * @param userId    用户ID
     * @param isLike    true=点赞，false=取消点赞
     * @return 操作结果（1=成功，0=重复操作）
     */
    @Override
    public int likeOrUnlike(String postId, String userId, boolean isLike) {
        // 构造 Redis Key
        String userKey = String.format(RedisKeys.CONTENT_LIKED_USERS, userId);
        String countKey = String.format(RedisKeys.CONTENT_LIKES_COUNT, postId);
        // 执行 Lua 脚本
        RedisScript<Long> script = isLike ? likeScript : unlikeScript;
        Long result = stringRedisTemplate.execute(
                script,
                List.of(userKey, countKey),
                userId
        );
        return result != null ? result.intValue() : 0;
    }

    /**
     * 检查用户是否点赞
     *
     * @param postId
     * @param userId
     * @return
     */
    @Override
    public Boolean isUserLiked(String postId, String userId) {
        String userKey = String.format(RedisKeys.CONTENT_LIKED_USERS, postId);
        return stringRedisTemplate.opsForSet().isMember(userKey, userId);
    }

    /**
     * 获取点赞数量
     *
     * @param postId
     * @return
     */
    @Override
    public Long getLikesCount(Long postId) {
        String countKey = String.format(RedisKeys.CONTENT_LIKES_COUNT, postId);
        String countStr = stringRedisTemplate.opsForValue().get(countKey); // 直接返回字符串
        //打印根据postId帖子的点赞数量
        log.info("帖子点赞数量：{}", countStr);
        if (countStr == null) {
            return 0L;
        }
        try {
            return Long.parseLong(countStr);
        } catch (NumberFormatException e) {
            log.error("Redis值格式错误: {} -> {}", countKey, countStr, e);
            return 0L;
        }
    }
}
